﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZLMsg;

namespace ZL_Framework.Game
{
    public class LogoPage : UIPanel, IMsgReceiver
    {
        public Slider loadingSlider;
        public override void OnOpen(IUIParam param)
        {
            base.OnOpen(param);
            if (!AppConfig.IsNet)
            {
                LogTool.Instance.Log("没有网络连接！");
                return;
            }
            CheckLoadRes();
        }

        private void CheckLoadRes()
        {
#if UNITY_EDITOR
            if (AppConfig.IsSimulate || !AppConfig.IsEmulation)
            {
                Timer.AddTimer(1).OnUpdated(UpdateProgress).OnCompleted(Loaded);
            }
            else
            {
                //从服务器热更资源
                ResourceUpdateManager.Instance.StartUpdateRes(UpdateResStart, UpdateResEnd, UpdateResProgress);
            }
#else
            if(!AppConfig.IsEmulation)
            {
                Timer.AddTimer(1).OnUpdated(UpdateProgress).OnCompleted(Loaded);
            }
            else
            {
                //从服务器热更资源
                //ResourceUpdateManager.Instance.StartUpdateRes(UpdateResStart, UpdateResEnd, UpdateResProgress);
            }
#endif
        }
        private void UpdateResStart(long size)
        {
            if (size > 0)
            {
                LogTool.Instance.Log("开始更新资源，大小：" + size / 1024f / 1024 + "m");
            }
            else
            {
                LogTool.Instance.Log("没有需要更新的资源");
            }
        }

        private void UpdateResEnd()
        {
            Loaded();
        }


        private void UpdateResProgress(float f)
        {
            UpdateProgress(f);
        }

        private void Loaded()
        {
            LogTool.Instance.Log("资源加载完成！");
            AssetBundlesManager.Instance.LoadLua(() =>
            {
                Timer.AddTimer(0.5f).OnCompleted(() =>
                {
                    this.RegisterLogicMsg(MsgName.MSG_CLOSE_LOGO_PAGE, CloseLogoPage);
                    LuaManager.Instance.StartLua();
                });
            });
        }

        private void UpdateProgress(float f)
        {
            loadingSlider.value = f;
        }

        private void CloseLogoPage(IMsgParam obj)
        {
            Close();
        }
    }
}